public class Solution930 {
    public int numSubarraysWithSum(int[] nums, int goal) {
        int[] count=new int[nums.length+1];
        int len=0;
        for (int num : nums) {
            if (num==0){
                count[len]++;
            }else{
                len++;
            }
        }
        if (goal>len){
            return 0;
        }
        if (goal!=0){
            int ans=0;
            for (int i=0;i<=len-goal;i++){
                ans=ans+(count[i]+1)*(count[i+goal]+1);
            }
            return ans;
        }else{
            int ans=0;
            for (int i=0;i<=len;i++){
                ans=ans+count[i]*(count[i]+1)/2;
            }
            return ans;
        }
    }

    public static void main(String[] args) {
        System.out.println(new Solution930().numSubarraysWithSum(new int[]{1,0,1,0,1},2));
    }
}
